# views.py
from django.shortcuts import render, redirect
from .models import Movie

def movie_list(request):
    # 从POST请求中获取当前页码，如果没有则默认为第一页
    if request.method == 'POST':
        current_page = int(request.POST.get('current_page', 1))
    else:
        current_page = 1
    
    # 每页显示3条记录
    per_page = 3
    all_movies = Movie.objects.all().order_by('title')
    total_movies = all_movies.count()
    total_pages = (total_movies + per_page - 1) // per_page
    
    # 计算分页范围
    start = (current_page - 1) * per_page
    end = start + per_page
    movies = all_movies[start:end]
    
    context = {
        'movies': movies,
        'current_page': current_page,
        'total_pages': total_pages,
    }
    
    return render(request, 'movies/movie_list.html', context)


def movie_list_2(request):
    # 从session中获取当前页码，如果没有则默认为第一页
    current_page = request.session.get('current_page', 1)

    # 每页显示3条记录
    per_page = 3
    all_movies = Movie.objects.all().order_by('title')
    total_movies = all_movies.count()
    total_pages = (total_movies + per_page - 1) // per_page

    # 处理"显示更多"按钮点击
    if request.method == 'POST' and 'show_more' in request.POST:
        current_page += 1
        if current_page > total_pages:
            current_page = 1  # 回到第一页

    # 保存当前页码到session
    request.session['current_page'] = current_page

    # 计算分页范围
    start = (current_page - 1) * per_page
    end = start + per_page
    movies = all_movies[start:end]

    context = {
        'movies': movies,
        'current_page': current_page,
        'total_pages': total_pages,
        'is_last_page': current_page == total_pages,
    }

    return render(request, 'movies/movie_list_2.html', context)
